/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:flutter/material.dart';
import 'package:hadss_adaptive_layout/hadss_adaptive_layout.dart';
import 'package:provider/provider.dart';

import '../../l10n/generated/app_localizations.dart';
import '../../main.dart';
import 'components/cardList.dart';
import 'components/top.dart';

class IMHomePage extends StatefulWidget {
  const IMHomePage({super.key});

  @override
  State<IMHomePage> createState() => _IMHomePageState();
}

class _IMHomePageState extends State<IMHomePage> with WidgetsBindingObserver {
  final int _currentIndex = 0;
  double _currentWidth = 0;
  double _currentHeight = 0;
  late WidthBreakpoint screenType;
  String textFieldValue = '';
  num topCurrentIndex = 0;
  bool isBigScreen = false;

  String activeName = 'Tom';

  bool navBarIsShow = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    updateScreenSize();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    updateScreenSize();
  }

  void updateScreenSize() {
    final Size size = WidgetsBinding.instance.window.physicalSize;
    final double ratio = WidgetsBinding.instance.window.devicePixelRatio;
    setState(() {
      _currentWidth = size.width / ratio;
      _currentHeight = size.height / ratio;
    });
  }

  Widget _buildVerticalNavButton(String label, int index,
      {required Widget activeIcon, Widget? deActiveIcon}) {
    deActiveIcon ??= activeIcon;
    return InkWell(
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 3),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _currentIndex == index ? activeIcon : deActiveIcon,
            Text(label,
                style: TextStyle(
                    color: _currentIndex == index
                        ? const Color(0xFF0A59F7)
                        : const Color.fromRGBO(0, 0, 0, 0.6),
                    fontSize: 10)),
          ],
        ),
      ),
    );
  }

  Widget renderNavigationPane(currentWidth, currentHeight, screenType, il8n) {
    return Stack(
      children: [
        Container(
          height: currentHeight,
          padding: const EdgeInsets.only(top: 40),
          decoration: const BoxDecoration(color: Colors.white),
          child: SingleChildScrollView(
            child: Container(
              color: const Color(0xFFFFFFFF),
              padding: const EdgeInsets.only(top: 10),
              child: Column(
                children: [
                  Head(
                    screenType: screenType,
                    currentWidth: currentWidth,
                  ),
                  CardList(
                      currentWidth: currentWidth,
                      activeName: activeName,
                      activeCallBack: (name) =>
                          setState(() => activeName = name)),
                  screenType == WidthBreakpoint.lg ||
                          screenType == WidthBreakpoint.xl
                      ? const SizedBox(
                          height: 10,
                        )
                      : const SizedBox(
                          height: 80,
                        )
                ],
              ),
            ),
          ),
        ),
        screenType == WidthBreakpoint.lg || screenType == WidthBreakpoint.xl
            ? Container()
            : Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Container(
                  width: currentWidth,
                  height: 76,
                  color: const Color(0xFFF2F3F4),
                  child: Container(
                    width: currentWidth,
                    height: 48,
                    margin: const EdgeInsets.only(bottom: 28),
                    decoration: const BoxDecoration(color: Color(0xFFF2F3F4)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        _buildVerticalNavButton(il8n.homePage, 0,
                            activeIcon: Image.asset(
                              'lib/assets/images/IM/1.png',
                              width: 24,
                              height: 24,
                            )),
                        _buildVerticalNavButton(il8n.addressBook, 1,
                            activeIcon: Image.asset(
                              'lib/assets/images/IM/4.png',
                              width: 24,
                              height: 24,
                            )),
                        _buildVerticalNavButton(il8n.socialCircle, 2,
                            activeIcon: Image.asset(
                              'lib/assets/images/IM/2.png',
                              width: 24,
                              height: 24,
                            )),
                        _buildVerticalNavButton(il8n.me, 3,
                            activeIcon: Image.asset(
                              'lib/assets/images/IM/3.png',
                              width: 24,
                              height: 24,
                            )),
                      ],
                    ),
                  ),
                ))
      ],
    );
  }

  Widget renderMainContent(currentWidth, currentHeight, screenType, il8n) {
    return Stack(
      children: [
        Container(
          height: currentHeight,
          padding: const EdgeInsets.only(top: 40),
          decoration: const BoxDecoration(color: Color(0xFFF1F3F5)),
          child: SingleChildScrollView(
            child: Container(
                color: const Color(0xFFF1F3F5),
                padding: const EdgeInsets.only(top: 10),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.all(6),
                              margin:
                                  const EdgeInsets.only(left: 10, right: 10),
                              decoration: BoxDecoration(
                                  color: const Color(0xFFE6E8E9),
                                  borderRadius: BorderRadius.circular(20)),
                              child: Image.asset(
                                  'lib/assets/images/chevron_backward.png'),
                            ),
                            Text(
                              activeName,
                              style: const TextStyle(
                                  fontWeight: FontWeight.w700, fontSize: 20),
                            ),
                          ],
                        ),
                        Container(
                            padding: const EdgeInsets.all(6),
                            margin: const EdgeInsets.only(left: 10, right: 10),
                            decoration: BoxDecoration(
                                color: const Color(0xFFE6E8E9),
                                borderRadius: BorderRadius.circular(20)),
                            child: Image.asset('lib/assets/images/more.png')),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        leftCard(il8n),
                        leftTextCard(il8n
                            .pleaseDrinkMilkTeaQuicklyOrderSpeedSpeedThatAllYouNeed),
                        rightTextCard(il8n.whatTheHappyEventToday),
                        const SizedBox(height: 100)
                      ],
                    )
                  ],
                )),
          ),
        ),
        Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.only(left: 20, right: 10),
              height: 80,
              decoration: const BoxDecoration(color: Color(0xFFF2F3F4)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Image.asset('lib/assets/images/ic_public_emoji.png'),
                  Expanded(
                    child: Container(
                      height: 34,
                      margin: const EdgeInsets.only(left: 10, right: 10),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.white60, width: 0.5),
                          borderRadius: BorderRadius.circular(20.0)),
                      child: const TextField(
                          decoration: InputDecoration(
                              contentPadding:
                                  EdgeInsets.only(top: 0, left: 15, bottom: 15),
                              border: InputBorder.none)),
                    ),
                  ),
                  Image.asset(
                      'lib/assets/images/Public_ic_public_add_norm.png'),
                ],
              ),
            ))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<RouteManager>(builder: (context, provider, child) {
      screenType = provider.widthBreakpoint;
      isBigScreen =
          screenType == WidthBreakpoint.lg || screenType == WidthBreakpoint.xl;
      return _contentView(context);
    });
  }

  Widget _contentView(BuildContext context) {
    AppLocalizations il8n = AppLocalizations.of(context)!;
    return Scaffold(
      body: Row(
        children: [
          if (isBigScreen)
            Container(
              width: 80, // 调整宽度
              color: const Color(0xFFF1F3F5),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(vertical: 15),
                    child: _buildVerticalNavButton(il8n.homePage, 0,
                        activeIcon: Image.asset(
                          'lib/assets/images/IM/1.png',
                          width: 24,
                          height: 24,
                        )),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  Container(
                      padding: const EdgeInsets.symmetric(vertical: 15),
                      child: _buildVerticalNavButton(il8n.addressBook, 1,
                          activeIcon: Image.asset(
                            'lib/assets/images/IM/4.png',
                            width: 24,
                            height: 24,
                          ))),
                  const SizedBox(
                    height: 20,
                  ),
                  Container(
                      padding: const EdgeInsets.symmetric(vertical: 15),
                      child: _buildVerticalNavButton(il8n.socialCircle, 2,
                          activeIcon: Image.asset(
                            'lib/assets/images/IM/2.png',
                            width: 24,
                            height: 24,
                          ))),
                  const SizedBox(
                    height: 20,
                  ),
                  Container(
                      padding: const EdgeInsets.symmetric(vertical: 15),
                      child: _buildVerticalNavButton(il8n.me, 3,
                          activeIcon: Image.asset(
                            'lib/assets/images/IM/3.png',
                            width: 24,
                            height: 24,
                          ))),
                ],
              ),
            ),
          Expanded(
              child: NavigationSplitContainer(
            navBarWidth: 320,
            mode: screenType == WidthBreakpoint.sm ||
                    screenType == WidthBreakpoint.xs
                ? NavigationSplitMode.stack
                : NavigationSplitMode.split,
            navigationPane: navBarIsShow
                ? renderNavigationPane(
                    _currentWidth, _currentHeight, screenType, il8n)
                : Container(),
            mainContent: navBarIsShow
                ? renderMainContent(
                    _currentWidth, _currentHeight, screenType, il8n)
                : renderNavigationPane(
                    _currentWidth, _currentHeight, screenType, il8n),
            onNavBarStateChange: (isVisible) {
              if (isVisible != navBarIsShow) {
                Future.delayed(Duration.zero, () {
                  setState(() {
                    navBarIsShow = isVisible;
                  });
                });
              }
            },
          ))
        ],
      ),
    );
  }
}

Widget leftCard(AppLocalizations il8n) {
  return Container(
    margin: const EdgeInsets.only(top: 30),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: const EdgeInsets.only(left: 10, right: 10),
          child: Image.asset('lib/assets/images/avatar/avatar_1.png'),
        ),
        Container(
          padding: const EdgeInsets.all(10),
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topRight: Radius.circular(20),
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        width: 16,
                        height: 16,
                        decoration: const BoxDecoration(
                            color: Color(0xFFF0A6C3),
                            borderRadius:
                                BorderRadius.all(Radius.circular(20))),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              il8n.tea,
                              style: const TextStyle(
                                  fontSize: 10, color: Colors.white),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                  Container(
                    margin: const EdgeInsets.only(left: 5),
                    child: Text(
                      il8n.milkTea,
                      style: const TextStyle(fontSize: 13),
                    ),
                  )
                ],
              ),
              Container(
                margin: const EdgeInsets.only(top: 5, bottom: 8),
                child: Text(il8n.fenfenInvitedYouToDrinkMilkTea,
                    style: const TextStyle(fontSize: 13)),
              ),
              Image.asset('lib/assets/images/im_Imag.png'),
              Container(
                margin: const EdgeInsets.only(top: 10),
                child: Text(
                  il8n.applet,
                  style: const TextStyle(fontSize: 11, color: Colors.black38),
                ),
              )
            ],
          ),
        )
      ],
    ),
  );
}

Widget leftTextCard(String text) {
  return Container(
    constraints: const BoxConstraints(maxWidth: 600),
    margin: const EdgeInsets.only(top: 30),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: const EdgeInsets.only(left: 10, right: 10),
          child: Image.asset('lib/assets/images/avatar/avatar_1.png'),
        ),
        Expanded(
          // 强制占满剩余宽度
          child: Container(
            padding: const EdgeInsets.all(10),
            margin: const EdgeInsets.only(right: 60),
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(20),
                    bottomLeft: Radius.circular(20),
                    bottomRight: Radius.circular(20))),
            child: Text(text), // 自动换行
          ),
        ),
      ],
    ),
  );
}

Widget rightTextCard(String text) {
  return Container(
    width: double.infinity,
    margin: const EdgeInsets.only(top: 30),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Container(
          padding: const EdgeInsets.all(10),
          decoration: const BoxDecoration(
              color: Color(0xFF0A59F7),
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20),
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20))),
          child: Text(
            text,
            style: const TextStyle(color: Colors.white),
          ),
        ),
        Container(
          margin: const EdgeInsets.only(left: 10, right: 10),
          child: Image.asset('lib/assets/images/avatar/avatar_2.png'),
        )
      ],
    ),
  );
}
